package com.laiketui.admin.store.controller.store;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.laiketui.admin.store.controller.store.entity.OrderDetailEntity;
import com.laiketui.admin.store.controller.store.util.AmountConverter;
import com.laiketui.core.utils.tool.DateUtil;
import com.laiketui.order.api.dto.OrderDetailDTO;
import com.laiketui.order.api.dto.StoreOrderDTO;
import com.laiketui.order.api.dto.WarehouseDTO;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.*;

@Service
public class ExportService {

    //导出采购单
    public Workbook export(StoreOrderDTO order) {
        // 模板路径
        String templatePath = "templates/admin_order_detail.xlsx";


        TemplateExportParams params = new TemplateExportParams(templatePath);
        Map<String, Object> data=new HashMap<>();
        data.put("orderNo", order.getOrderNo());
        data.put("orderParentNo", order.getOrderParentNo());
        data.put("createTime", DateUtil.dateFormate(order.getCreateTime(), "yyyy-MM-dd"));
        data.put("brands", order.getBrands());
        data.put("warehouseName", order.getFactoryAddress().getName());

        data.put("name",order.getName());
        WarehouseDTO address = order.getDeliveryAddress();
        data.put("deliveryName",address.getName());
        data.put("deliveryMobile",address.getMobile());
        data.put("deliveryProvice", address.getProvice());
        data.put("deliveryCity", address.getCity());
        data.put("deliveryArea", address.getArea());
        data.put("deliveryAddress", address.getAddress());
        String specifyDeliveryTime="";
        if(Objects.nonNull(order.getSpecifyDeliveryTime())){
            specifyDeliveryTime= DateUtil.dateFormate(order.getSpecifyDeliveryTime(), "yyyy/MM/dd");
        }
        data.put("specifyDeliveryTime", specifyDeliveryTime);
        data.put("opRemark", order.getOpRemark());
        data.put("mchRemark", order.getMchRemark());
        List<OrderDetailDTO> details = order.getDetails();
        List<OrderDetailEntity> dtOs = new ArrayList<>();
        int nums = 0;
        int bagNums=0;
        for (int i = 0; i < details.size(); i++) {
            OrderDetailDTO dto = details.get(i);
            OrderDetailEntity orderDetailEntity = new OrderDetailEntity();
            BeanUtils.copyProperties(dto, orderDetailEntity);
            orderDetailEntity.setSort(i + 1);
            setImageEntity(orderDetailEntity);
            nums += orderDetailEntity.getNum();
            bagNums += orderDetailEntity.getBomNum();
            dtOs.add(orderDetailEntity);
        }
        data.put("totalNums",nums);
        data.put("totalBomNums",bagNums);
//        BigDecimal value = order.getTotalPrice();
        BigDecimal value = order.getSettlementAmount();
        data.put("totalPrice", value);
        String chineseUpperCaseAmount = AmountConverter.toChineseUpperCase(value);
        data.put("opTotalPriceM", chineseUpperCaseAmount);

        data.put("orderDetails",dtOs);


        Workbook workbook = ExcelExportUtil.exportExcel(params, data);

        Sheet sheet = workbook.getSheetAt(0);


        for (int i = 0; i < dtOs.size(); i++) {
            int index=9 + i;
            sheet.addMergedRegionUnsafe(new CellRangeAddress(index, index, 2, 3));
            sheet.addMergedRegionUnsafe(new CellRangeAddress(index, index, 8, 9));
            sheet.addMergedRegionUnsafe(new CellRangeAddress(index, index, 10, 11));
            sheet.addMergedRegionUnsafe(new CellRangeAddress(index, index, 10, 11));
            sheet.addMergedRegionUnsafe(new CellRangeAddress(index, index, 12, 13));
            sheet.addMergedRegionUnsafe(new CellRangeAddress(index, index, 14, 15));
        }

        CellStyle style = createStyle(workbook);
        style.setAlignment(HorizontalAlignment.CENTER);

        CellStyle styleRight = createStyle(workbook);
        styleRight.setAlignment(HorizontalAlignment.RIGHT);

        CellStyle styleLeft = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("等线(正文)");
        font.setBold(true);
        font.setFontHeightInPoints((short) 14);
        styleLeft.setFont(font);
        styleLeft.setVerticalAlignment(VerticalAlignment.CENTER);
        styleLeft.setAlignment(HorizontalAlignment.LEFT);

        int lastRowNum = 8+dtOs.size();
        lastRowNum++;
        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 0, 5));
        Row row = sheet.createRow(lastRowNum);
        row.setHeight((short) 600);
//        row.setRowStyle(style);
        CellStyle borderStyle = createBorderStyle(workbook);
        createCell(row, borderStyle);

        Cell cell1 = row.createCell(0);
        cell1.setCellValue("合计:");
        cell1.setCellStyle(styleRight);

        row.createCell(6).setCellStyle(style);
        row.createCell(7).setCellStyle(style);
        int i = sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 8, 9));
        Cell cell = row.createCell(8);
        cell.setCellValue(nums);
        cell.setCellStyle(style);

        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 10, 11));
        Cell cellBom = row.createCell(10);
        cellBom.setCellValue(bagNums);
        cellBom.setCellStyle(style);



        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 12, 13));
        Cell cellTotalPrice = row.createCell(12);
        cellTotalPrice.setCellValue(value.toString());
        cellTotalPrice.setCellStyle(style);


        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 14, 15));


        //金额大写
        lastRowNum++;
        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 0, 5));
        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 6, 15));
        row = sheet.createRow(lastRowNum);
        row.setHeight((short) 600);
//        row.setRowStyle(style);
        createCell(row, borderStyle);

        Cell cell3 = row.createCell(0);
        cell3.setCellValue("合计大写总金额:");
        cell3.setCellStyle(styleRight);
        cell3.getCellStyle().setAlignment(HorizontalAlignment.RIGHT);

        Cell cellAmountM=row.createCell(6);
        cellAmountM.setCellValue(chineseUpperCaseAmount);
        cellAmountM.setCellStyle(style);


        lastRowNum++;
        row = sheet.createRow(lastRowNum);
        row.setHeight((short) 2000);

        lastRowNum++;
        row = sheet.createRow(lastRowNum);
        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 0, 2));
        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 3, 5));
        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 6, 10));
        cell=row.createCell(0);
        cell.setCellValue("制作人:");
        cell.setCellStyle(styleLeft);


        cell=row.createCell(3);
        cell.setCellValue("财务审核:");
        cell.setCellStyle(styleLeft);


        cell=row.createCell(6);
        cell.setCellValue("核准人:");
        cell.setCellStyle(styleLeft);


        return workbook;
    }

    private static void createCell(Row row, CellStyle borderStyle) {
        for (int j=0;j<16;j++){
            row.createCell(j).setCellStyle(borderStyle);
        }
    }


    public Workbook exportMchOrder(StoreOrderDTO order) {
        // 模板路径
        String templatePath = "templates/admin_order_mch.xlsx";


        TemplateExportParams params = new TemplateExportParams(templatePath);
        Map<String, Object> data=new HashMap<>();
        data.put("orderNo", order.getOrderNo());
        data.put("orderParentNo", order.getOrderParentNo());
        data.put("createTime", DateUtil.dateFormate(order.getCreateTime(), "yyyy-MM-dd"));
        data.put("brands", order.getBrands());
        data.put("warehouseName", order.getFactoryAddress().getName());

        data.put("name",order.getName());
        WarehouseDTO address = order.getDeliveryAddress();
        data.put("deliveryName",address.getName());
        data.put("deliveryMobile",address.getMobile());
        data.put("deliveryProvice", address.getProvice());
        data.put("deliveryCity", address.getCity());
        data.put("deliveryArea", address.getArea());
        data.put("deliveryAddress", address.getAddress());
        String specifyDeliveryTime="";
        if(Objects.nonNull(order.getSpecifyDeliveryTime())){
            specifyDeliveryTime= DateUtil.dateFormate(order.getSpecifyDeliveryTime(), "yyyy/MM/dd");
        }
        data.put("specifyDeliveryTime", specifyDeliveryTime);
        data.put("opRemark", order.getOpRemark());
        data.put("mchRemark", order.getMchRemark());
        List<OrderDetailDTO> details = order.getDetails();
        List<OrderDetailEntity> dtOs = new ArrayList<>();
        int nums = 0;
        int bagNums=0;
        for (int i = 0; i < details.size(); i++) {
            OrderDetailDTO dto = details.get(i);
            OrderDetailEntity orderDetailEntity = new OrderDetailEntity();
            BeanUtils.copyProperties(dto, orderDetailEntity);
            orderDetailEntity.setSort(i + 1);
            setImageEntity(orderDetailEntity);
            nums += orderDetailEntity.getNum();
            bagNums += orderDetailEntity.getBomNum();
            dtOs.add(orderDetailEntity);
        }
        data.put("totalNums",nums);
        data.put("totalBomNums",bagNums);
        BigDecimal value = order.getSettlementAmount();
        data.put("totalPrice", value);
        String chineseUpperCaseAmount = AmountConverter.toChineseUpperCase(value);
        data.put("opTotalPriceM", chineseUpperCaseAmount);

        data.put("orderDetails",dtOs);


        Workbook workbook = ExcelExportUtil.exportExcel(params, data);

        Sheet sheet = workbook.getSheetAt(0);


        for (int i = 0; i < dtOs.size(); i++) {
            int index=9 + i;
            sheet.addMergedRegionUnsafe(new CellRangeAddress(index, index, 2, 3));
            sheet.addMergedRegionUnsafe(new CellRangeAddress(index, index, 8, 9));
            sheet.addMergedRegionUnsafe(new CellRangeAddress(index, index, 10, 11));
            sheet.addMergedRegionUnsafe(new CellRangeAddress(index, index, 12, 15));
        }

        CellStyle style = createStyle(workbook);
        style.setAlignment(HorizontalAlignment.CENTER);

        CellStyle styleRight = createStyle(workbook);
        styleRight.setAlignment(HorizontalAlignment.RIGHT);

        CellStyle styleLeft = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("等线(正文)");
        font.setBold(true);
        font.setFontHeightInPoints((short) 14);
        styleLeft.setFont(font);
        styleLeft.setVerticalAlignment(VerticalAlignment.CENTER);
        styleLeft.setAlignment(HorizontalAlignment.LEFT);

        int lastRowNum = 8+dtOs.size();
        lastRowNum++;
        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 0, 5));
        Row row = sheet.createRow(lastRowNum);
        row.setHeight((short) 600);
//        row.setRowStyle(style);
        CellStyle borderStyle = createBorderStyle(workbook);
        createCell(row, borderStyle);
        Cell cell1 = row.createCell(0);
        cell1.setCellValue("合计:");
        cell1.setCellStyle(styleRight);

        row.createCell(6).setCellStyle(style);
        row.createCell(7).setCellStyle(style);
        int i = sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 8, 9));
        Cell cell = row.createCell(8);
        cell.setCellValue(nums);
        cell.setCellStyle(style);




        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 10, 11));
        Cell cellTotalPrice = row.createCell(10);
        cellTotalPrice.setCellValue(value.toString());
        cellTotalPrice.setCellStyle(style);

        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 12, 15));

        //金额大写
        lastRowNum++;
        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 0, 5));
        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 6, 15));
        row = sheet.createRow(lastRowNum);
        row.setHeight((short) 600);
//        row.setRowStyle(style);
        createCell(row, borderStyle);
        Cell cell3 = row.createCell(0);
        cell3.setCellValue("合计大写总金额:");
        cell3.setCellStyle(styleRight);
        cell3.getCellStyle().setAlignment(HorizontalAlignment.RIGHT);

        Cell cellAmountM=row.createCell(6);
        cellAmountM.setCellValue(chineseUpperCaseAmount);
        cellAmountM.setCellStyle(style);

        lastRowNum++;
        row = sheet.createRow(lastRowNum);
        row.setHeight((short) 2000);

        lastRowNum++;
        row = sheet.createRow(lastRowNum);
        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 0, 2));
        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 3, 5));
        sheet.addMergedRegion(new CellRangeAddress(lastRowNum, lastRowNum, 6, 10));
        cell=row.createCell(0);
        cell.setCellValue("制作人:");
        cell.setCellStyle(styleLeft);


        cell=row.createCell(3);
        cell.setCellValue("财务审核:");
        cell.setCellStyle(styleLeft);


        cell=row.createCell(6);
        cell.setCellValue("核准人:");
        cell.setCellStyle(styleLeft);


        return workbook;
    }





    private static @NotNull CellStyle createStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        // 设置边框
        style.setBorderTop(BorderStyle.THIN); // 顶部边框
        style.setBorderBottom(BorderStyle.THIN); // 底部边框
        style.setBorderLeft(BorderStyle.THIN); // 左边边框
        style.setBorderRight(BorderStyle.THIN); // 右边边框
        Font font = workbook.createFont();
        font.setFontName("等线(正文)");
        font.setBold(true);
        font.setFontHeightInPoints((short) 14);
        style.setFont(font);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }
    private static @NotNull CellStyle createBorderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        // 设置边框
        style.setBorderTop(BorderStyle.THIN); // 顶部边框
        style.setBorderBottom(BorderStyle.THIN); // 底部边框
        style.setBorderLeft(BorderStyle.THIN); // 左边边框
        style.setBorderRight(BorderStyle.THIN); // 右边边框
        return style;
    }

    private static void setImageEntity(OrderDetailEntity orderDetailDTO) {
        URL imageUrl = null;
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        try {
            imageUrl = new URL(orderDetailDTO.getImg());
            BufferedImage bufferImg = ImageIO.read(imageUrl);
            ImageIO.write(bufferImg, "jpg", byteArrayOut);
            ImageEntity imageEntity = new ImageEntity(byteArrayOut.toByteArray(), 100, 50);
            orderDetailDTO.setImageEntity(imageEntity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                byteArrayOut.close();
            } catch (IOException e) {

            }
        }
    }

}
